package com.fly.springbootTemplate.config;

import com.auth0.jwt.exceptions.AlgorithmMismatchException;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fly.springbootTemplate.utils.JWTUtils;
import com.fly.springbootTemplate.utils.ResultCode;
import com.fly.springbootTemplate.utils.ResultCodeEnum;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JWTInterceptrors implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String message = "";
        String token = request.getHeader("token");
        try{
            JWTUtils.verity(token);
            return true;
        }catch (SignatureVerificationException e){
            message = "无效签名!";
        }catch (TokenExpiredException e){
            message = "token过期了";
        }catch (AlgorithmMismatchException e){
            message = "token 为空或无效!";
        }
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(ResultCode.failure(ResultCodeEnum.UNAUTHORIZED,message));
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(json);
        return false;
    }
}
